import {Component, OnInit, ViewEncapsulation, ViewChild, OnDestroy} from '@angular/core';

import {Subject} from "rxjs/Subject";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {SignUpService} from "@sign-up/sign-up.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {MatchSignUpData, MatchSignupFieldsResp} from "@interface/index";
// import {MatchSignupFieldsResp} from "@interface/match/match.model";
// import {MatchSignUpData} from "@interface/shared/shared.model";


@Component({
  selector: 'seed-group-competition',
  templateUrl: './sign-up-group-match.component.html',
  styleUrls: ['./sign-up-group-match.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class SignUpGroupMatchComponent implements OnInit, OnDestroy {

  public firstLoad = true;
  public signing = false;
  public addition: MatchSignupFieldsResp[];
  public params = new MatchSignUpData();
  private ngUnsubscribe: Subject<void> = new Subject<void>();

  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  constructor(
    private signUpService: SignUpService,
    private route: ActivatedRoute,
    private toolsService: ToolsService,
    public auth: AuthService,
    public router: Router
    ) {
  }

  getData() {
    if (this.firstLoad) {
      this.toolsService.showLoading();
    }
    this.signUpService.getDynamicMatchInfo(this.params.matchId, this.params.orderNumber)
      .subscribe((res) => {
        this.toolsService.hideLoading();
        if (res.result === '0') {
          if (res.data.matchSignupFields.length > 0) {
            this.addition = res.data.matchSignupFields;
          }
        }
      });
  }

  sign(chooseArr) {
    if (this.signing) {
      return;
    }
    this.signing = true;
    const data = this.signUpService.getPerasonalSignData(this.params);

    data['members'] = chooseArr;
    this.toolsService.showLoading();
    this.signUpService
      .addMatchTeamSign(data)
      .subscribe((res) => {
        this.signing = false;
        this.toolsService.hideLoading();
        if (res['result'] === '0') {
          if (res.data.list.length > 0) {  // 如果已经创建了俱乐部
            this.router.navigate(['/sign-up/group/choose-club'], {queryParams: {orderNumber: this.params.orderNumber}});
          } else {
            this.router.navigate(['/sign-up/group/create-club'], {queryParams: {orderNumber: this.params.orderNumber}});
          }
        } else if (res.result === '9012') {
          this.toolsService.showToast('该商品已下架');
        } else if (res.result === '13002') {
          this.toolsService.showToast('提交失败，请查看订单状态是否正常');
        } else if (res.result === '10011' || res.result === '10017') { // 人数限制
          this.toolsService.showToast(this.getBuyLimitMsg(res.data));
        } else if (res.result === '10013') {  // 用户已报名了;
          const str = this.signUpService.getHasSignMemberStr(res.data);
          const temp = {
            title: '用户已报名',
            message: str
          };
          this.toolsService.present(temp);
        } else if (res.result === '10012') {  // 年龄限制;
          const msgData = this.signUpService.getAgeLimitMsg(res.data);
          const temp = {
            title: `参赛人年龄不符 ${msgData.minAge} ~ ${msgData.maxAge} 岁`,
            message: `报名人: ${msgData.memberStr}`
          };
          this.toolsService.present(temp);
        } else {
          this.toolsService.showToast(res.msg);
        }
      });
  }

  /**
   * @description  请求报名接口返回的人数不符
   * @author ouxh
   * @date 2017-10-26
   * @param data : {playNumber: number}
   * @return string
   */
  getBuyLimitMsg(data: any) {
    return data.maxPlayerNumber ?
      `该赛事报名人数必须介于 ${data.playerNumber} 到 ${data.maxPlayerNumber} 人之间`
      : `您已购买了${data.playerNumber}位名额, 请选择${data.playerNumber}位参赛人`;
  }

  ngOnInit() {
    this.toolsService.setTitle('报名人信息');
    this.route.queryParams.takeUntil(this.ngUnsubscribe).subscribe((param) => {
      this.params.channelsId = param['channelsId'];
      this.params.matchId = param['matchId'];
      this.params.groupType = param['goodsType'];
      this.params.orderNumber = param['orderNumber'];
    });
    this.getData();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
